<template>
  <FPage>
    <template #header>
      <div style="padding: 5px">
        <el-tree-select
          style="width: 100%"
          v-model="selectedUnit"
          :data="unitTree" default-expand-all
          check-strictly node-key="id"
          :props="defaultProps"
          @change="loadRoles"
          :render-after-expand="false"
        />
      </div>
    </template>
    <FListV2 :selected-key="roleKey" size="small"
             title-name="roleName" :data-source="roles"
             @select="selectRole" @doubleClick="createRoleConfig"
             v-loading="loading"></FListV2>
  </FPage>
</template>

<script setup>
import {getAction} from '@/request/BaseRequest';
import {guid, isEmpty, listToTrees, real} from '@/utils/CommonUtils';
import {UserConfig} from '@/components/UserSelectorModal/DefaultUserConfig';
import {onMounted, shallowRef} from 'vue';
import FListV2 from '@/components/FListV2/index.vue';
import FPage from '@/components/layout/FPage.vue';
import {useStore} from 'vuex';

const selectedUnit = shallowRef();
const roleKey = shallowRef();
const loading = shallowRef(false);
const roles = shallowRef([]);
const emits = defineEmits(['create']);
const unitTree = shallowRef([]);
const store = useStore();
let userInfo = undefined;
const defaultProps = {
  children: 'children',
  label: 'unitName',
};


onMounted(() => {
  userInfo = real(store.getters['user/userInfo']);
  selectedUnit.value = userInfo.unitId;
  loadRoles();
  loadUnits();
});

function loadUnits() {
  getAction('/sys/unit/loadUnits').then(data => {
    if (data.success) {
      let result = data.result;
      setUnitTree(result);
    }
  });
}

function setUnitTree(list) {
  if (isEmpty(list)) list = [];
  unitTree.value = listToTrees(list);
}

function createRoleConfig(role) {
  let res = JSON.parse(JSON.stringify(UserConfig));
  res.type = 'role';
  res.roleId = role.id;
  res.roleName = role.roleName;
  res.configName = role.roleName;
  res.id = guid();
  emits('create', res);
}

function loadRoles() {
  loading.value = true
  getAction('/base/baseRole/loadRolesByUnitId', {
    unitId: selectedUnit.value
  }).then(data => {
    loading.value = false
    if (data.success) {
      if (isEmpty(data.result)) data.result = [];
      roles.value = data.result;
    }
  })
}

function selectRole(role) {
  roleKey.value = role.id;
}

</script>

<script>
export default {
  name: 'RoleList'
}
</script>

<style scoped>

</style>
